// var webUrl = "http://wdzn-kh:8087"
// var webUrl = "http://10.11.0.57:8087";
var webUrl = window.location.host;
webUrl = 'http://' + webUrl;

// 发送带token的ajax的Post类型为JSON请求
function sendPostJsonAjax(url, data, callback) {
  data.token = getCookie("token");
  data = JSON.stringify(data);
  $.ajax({
    url: url,
    type: 'post',
    dataType: 'json',
    contentType: "application/json;charset=utf-8",
    data: data,
    success: callback,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      layui.use(["layer", "element"], function () {
        var layer = layui.layer;
        layer.close(layer.index)
        layer.open({
          type:1,
          content:'<div> 后台数据连接失败</div>',
          btn:['确认'],
          area: ['200', '100'],
          success:function(index,layero)
          {
            //窗体弹出后回调方法

          },
          yes:function(index,layero)
          {
            window.parent.returnLogin();
          } });
      });
    }
  })
}

// 发送带token的ajax的Post请求
function sendPostAjax(url, data, callback) {
  data.token = getCookie("token");
  $.ajax({
    url: url,
    type: 'post',
    data: JSON.stringify(data),
    dataType: 'json',
    contentType: "application/json;charset=utf-8",
    success: callback,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      layui.use(["layer", "element"], function () {
        var layer = layui.layer;
        layer.close(layer.index)
      });
    }
  })
}
// 发送不解析数据的ajax的Post请求
function sendPost(url, data, callback) {
  $.ajax({
    url: url,
    type: 'post',
    dataType: 'json',
    data: data,
    contentType: "application/json;charset=utf-8",
    success: callback,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      layui.use(["layer", "element"], function () {
        var layer = layui.layer;
        layer.close(layer.index)
        layer.open({
          type:1,
          content:'<div> 后台数据连接失败</div>',
          btn:['确认'],
          area: ['200', '100'],
          success:function(index,layero)
          {
            //窗体弹出后回调方法

          },
          yes:function(index,layero)
          {
            window.parent.returnLogin();
          } });
      });
    }
  })
}
// 发送没带token的ajax的Post请求
function sendPostWitoutoKen(url, data, callback) {
  $.ajax({
    url: url,
    type: 'post',
    dataType: 'json',
    contentType: "application/json;charset=utf-8",
    data: data,
    success: callback,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      layui.use(["layer", "element"], function () {
        var layer = layui.layer;
        layer.close(layer.index)
        layer.open({
          type:1,
          content:'<div> 后台数据连接失败</div>',
          btn:['确认'],
          area: ['200', '100'],
          success:function(index,layero)
          {
            //窗体弹出后回调方法

          },
          yes:function(index,layero)
          {
            window.parent.returnLogin();
          } });
      });
    }
  })
}

// ajax get 请求
function sendGetAjax(url, params, successfn) {
  $.ajax({
    url: url,
    type: "get",
    dataType: "json",
    header: { token: getCookie("token") },
    data: params,
    success: successfn,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      layui.use(["layer", "element"], function () {
        var layer = layui.layer;
        layer.close(layer.index)
        layer.open({
          type:1,
          content:'<div> 后台数据连接失败</div>',
          btn:['确认'],
          area: ['200', '100'],
          success:function(index,layero)
          {

          },
          yes:function(index,layero)
          {
            window.parent.returnLogin();
          } });

      });
    }
  })
}
function sendPostAjaxWithParams(url, params, successfn) {
  $.ajax({
    url: url,
    type: "post",
    dataType: "json",
    header: { token: getCookie("token") },
    data: params,
    success: successfn,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      layui.use(["layer", "element"], function () {
        var layer = layui.layer;
        layer.close(layer.index)
      });
    }
  })
}

//设置cookie
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toGMTString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

//获取cookie
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); }
  }
  return "";
}

//浮点数减法运算
function floatSub(arg1, arg2) {
  var r1, r2, m, n;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2));
  //动态控制精度长度  
  n = (r1 >= r2) ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(2);
}

//浮点数加法运算
function FloatAdd(arg1, arg2) {
  var r1, r2, m;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2));
  return (arg1 * m + arg2 * m) / m;
}

//返回登录
function returnLogin() {
  setCookie("userName", "");
  setCookie("menuList", "");
  setCookie("name", "");
  setCookie("token", "");
  setCookie("rolename", "");
  window.location.href = webUrl;
  /* 	  window.location.href = 'http://localhost:8080/ERP/login.html' */
  return;

}

function loadByImport(uri, callback, t, params) {
  var text = t ? t : '错误信息'
  var html =
    '<a style="margin:40px 40px;width:220px;" type="button" class="layui-btn upload">' +
    '<input class="change" type="file" id="uploadBtn" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />' +
    '<div class="icon"><i class="layui-icon">&#xe67c;</i>上传文件</div>' +
    '</a>'

  var index = layer.open({
    type: 1,
    title: '上传Excel文件',
    content: html
  });
  $("#uploadBtn").change(function () {
    uploadLoad = layer.load(2, { shade: 0.1 });
    var fileObj = document.getElementById("uploadBtn").files[0];
    var formData = new FormData();
    formData.append("token", getCookie("token"));
    formData.append("excelPath", fileObj);
    if (params && Object.prototype.toString.call(params) === '[object Object]') {
      for (let key in params) {
        if (!params.hasOwnProperty(key)) continue;
        formData.append(key, params[key]);
      }
    }
    var url = webUrl + uri;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);        // 也可以使用POST方式，根据接口
    xhr.responseType = "blob";    // 返回类型blob
    // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
    xhr.onload = function () {
      // 请求完成
      if (this.status === 200 || this.status === 304) {
        layer.close(uploadLoad);
        // 返回200
        var blob = this.response;
        if (this.response.type !== "application/json") {
          layer.close(index);
          var reader = new FileReader();
          reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
          reader.onload = function (e) {
            // 转换完成，创建一个a标签用于下载
            var a = document.createElement('a');
            a.download = text + '.xlsx';
            a.href = e.target.result;
            $("body").append(a);    // 修复firefox中无法触发click
            a.click();
            $(a).remove();
            layer.msg('导入失败', { time: 1000 });
          }
        } else {
          layer.close(index);
          callback(1);
          var reader = new FileReader();
          reader.readAsText(blob, 'utf-8')
          reader.onload = function (e) {
            var msg = JSON.parse(e.currentTarget.result).errMsg
            layer.alert(msg);
          }
        }
      }
    };
    xhr.error = function () {
      layer.close(uploadLoad);
      layer.close(index);
      layer.alert("请求异常");
    }
    // 发送ajax请求
    xhr.send(formData)
  })
}
